const express = require('express')
//路由对象
const userRouter = express.Router() 


//用户数组
const userList = [{ username: 'admin', password: 123 }]

//3.创建路由
/**
 *  客户端： 输入用户名username和密码password
 *     http://ip:port/login?username=admin&password=123
 *
 *  服务端:  1.接收用户名username和密码password
 *          2. 判断用户名密码是否已经存在
 */
userRouter.get('/login', (req, res) => {
	// 1. 接收请求
	const username = req.query.username
	const password = req.query.password
	// 2. 处理业务逻辑
	const user = userList.find(item => item.username == username && item.password == password)
	if (user) {
		// 3. 响应数据
		res.send({
			code: 1,
			message: '登录成功',
		})
	} else {
		// 3. 响应数据
		res.send({
			code: -1,
			message: '用户名或密码出错!',
		})
	}
})

/**
 * 注册
 *   客户端:  http://ip:port/register?username=root&password=123456
 *
 *
 */
userRouter.get('/register', (req, res) => {
	//1 接收参数
	const username = req.query.username
	const password = req.query.password
	//2.注册业务逻辑
    const user = { username: username, password: password }
	userList.push(user) 
    /**
     * [
     *   { username: 'admin', password: 123 },
     *   { username: 'root', password: 123456 }
     * ]
     */
	//3.响应注册成功
	res.send({
        code:1,
        message:'注册成功'
    })
})

/**
 * 删除用户
 *   http://ip:port/delete?username=admin
 */
userRouter.get('/delete',(req,res)=>{
	// 1. 接收请求
	const username = req.query.username
	// 2. 删除用户数组中元素
	const index = userList.findIndex(item=>item.username == username) // 查找满足条件的元素索引号
	userList.splice(index,1) //删除从索引号0开始的1个元素
	// 3. 响应数据
	res.send({
		code:1,
		message:'删除成功!'
	})
})

/**
 * 显示所有用户
 */
userRouter.get('/user/list',(req,res)=>{
	res.send({
		code:1,
		list:userList
	})
})

module.exports = {userRouter}